
	<!--地图层 -->

	<div id="container" style="display: none;position: fixed;top: 0px;left:0px;right:0px;bottom:0px;z-index: 22;background: #fff;">
		<div id="googleMap" style="width:100%;height:100%;"></div>
		<div id="init_city"></div>
	</div>

<style>
	.custom-map-control-button{margin:20px 2px;border-radius: 15px;border-width: 1px;box-shadow: 1px 1px 3px #f60;padding:4px 8px;}
</style>
<script type="text/javascript">

	// google.maps.MapTypeId.HYBRID      ：显示卫星图像的主要街道透明层
	// google.maps.MapTypeId.ROADMAP      ：显示普通的街道地图
	// google.maps.MapTypeId.SATELLITE    ：显示卫星图像

	
	//路线数据
	var route_obj={
		address_start:'',
		address_end:'',
		distance: 0,
		duration:''
	};

	//加载地图资源
	function loadScript(){
	  var script = document.createElement("script");
	  script.type = "text/javascript";
	  script.src = "https://maps.googleapis.com/maps/api/js?key=AIzaSyB6GHAYtKuxzrTKcbwi6VWg65TmOuI5608&libraries=places&sensor=true&callback=initialize";
	  document.body.appendChild(script);
	}

	var outTextQuery=null;
	var outCalcRoute=null;
	var a_find=0;
	var current_pos='';

	//地图初始化函数，定义地图中心，属性，类型等
	function initialize(){
		var infoWindow;
		var center=new google.maps.LatLng(11.569593, 104.920915);
		
		//地图属性
		var mapProp = {
			center: center,
			zoom:15,
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			panControl:false,
			zoomControl:true,
			mapTypeControl:false,
			scaleControl:true,
			streetViewControl:false,
			overviewMapControl:true,
			rotateControl:false
		};

		//地图建立
		var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);


		//路线服务与渲染
		var directionsService = new google.maps.DirectionsService();
		var directionsRenderer = new google.maps.DirectionsRenderer();				
		directionsRenderer.setMap(map);
	

		//一个信息窗口
		// var infowindow = new google.maps.InfoWindow({
		// 	content:"我们在这里!"
		// });
		// infowindow.open(map,marker);


		//地理定位到当前位置,需要准备一些东西//////////////////////////////////////////////////
		infoWindow = new google.maps.InfoWindow({content:'Location found!'});

		const closeMapButton = document.createElement("button");
		const calcRouteButton = document.createElement("button");

		//addtional buttons 
		calcRouteButton.textContent = "路线规划";
		closeMapButton.textContent = "退出(Exit)";

		calcRouteButton.classList.add("custom-map-control-button");
		closeMapButton.classList.add("custom-map-control-button");

		map.controls[google.maps.ControlPosition.BOTTOM].push(calcRouteButton);
		map.controls[google.maps.ControlPosition.BOTTOM].push(closeMapButton);


		//找出当前的定位
		function whereIsHere(){
			// Try HTML5 geolocation.
			if (navigator.geolocation) {
				navigator.geolocation.getCurrentPosition(
				  success=>{

				  	//console.log(success);
					const pos = {
						lat: success.coords.latitude,
						lng: success.coords.longitude,
					};

					//显示位置信息
					setMarker(pos,'');
					map.panTo(pos);
					//setTimeout(function(){setInfo(pos,"let's go!!!!!!!!!!!!!",map);},2000)
					center =  pos;
					current_pos = pos;
					find_city(pos);

				}
				,function(error){alert(error.message);}//定位出错的信息显示
				,{
				 //可增加的4个配置参数
				  enableHighAccuracy:true,//高精度
				  timeout:5000,//超时时间,以ms为单位
				  maximumAge:24*60*60*1000,//位置缓存时间,以ms为单位
				}
				);
			} else {
				alert("Browser doesn't support Geolocation");

			}
		}
		whereIsHere();
		////定位当前位置////////////////////////////////////////////////// 

		//auto location current city
		function find_city(pos){
			var request = {
				location: center,
				radius: '1000',
			};

			var service = new google.maps.places.PlacesService(map);
			service.nearbySearch(request,function(results, status) {
			  if (status == google.maps.places.PlacesServiceStatus.OK) {
			  	
			    var city=results[0].name;
			    document.getElementById('init_city').innerText = city?city:'';
			    //drawCircle(center,500);
			  }else{

			  	alert('Sorry,you are in an unknow place!');
			  }
			});
		}



		//清除markers
		function cleanMarkers(){
			console.log('There are '+markers.length+' markers,now clean markers...');

			for(i in markers){
				markers[i].setMap(null);
				markers[i]=null;
			}
			markers.length=0;
			console.log('There are '+markers.length+" markers");


			for(i in circles){
				circles[i].setMap(null);
			}
			circles.length=0;

		}

		//退出地图
		closeMapButton.addEventListener('click',function(){
			document.getElementById('container').style.display='none';
			document.getElementById('mask').style.display='none';
		});

		
		//做标记，标记内容，信息窗
		var markers=[]; //标记数组

		function setMarker(pos,txt='',placeId=''){
			console.log({'pos in setMarker':pos,'placeId':placeId});
			var marker=new google.maps.Marker({
				position:pos,
				map,
				//icon:svgMarker
				//animation:google.maps.Animation.BOUNCE //一动一动的图标
			});

			if(txt) {marker.setLabel(txt+'');}
			markers.push(marker);
				
			//做自己的标记
			if(placeId){
				google.maps.event.addListener(marker, 'click', function() {
					console.log(placeId);
				

					//查出图标的详细资料
					var service = new google.maps.places.PlacesService(map);	
					var request = {
						placeId:placeId
					};

					service.getDetails(request,function(result,status){
						if(status=='OK'){
							console.log({status:status,result:result});
							var infoTxt = "<div style='font-weight:bold;color:blue;'>"+result.name+"</div><div>"+result.formatted_address+"</div>";
								infoTxt+="<div style='border-top:1px solid #ccc;'><a style='color:blue;' href='"+result.url+"'>Google for this place</a></div>";
							setInfo(pos,infoTxt,map);
							
							calcRoute();

						}else{
							alert('From google:['+status+']');
						}

					});


				});
			}

			//marker.setMap(map); 
		}


		/*路线规划
		directionsService的返回值status如下:
		1.OK 表示响应中包含有效的 DirectionsResult。
		2.NOT_FOUND 表示请求的出发地、目的地或航点中指定的位置中至少有一个无法接受地理编码。
		3.ZERO_RESULTS 表示在出发地和目的地之间找不到路线。
		4.MAX_WAYPOINTS_EXCEEDED 表示 DirectionsRequest 中提供的 DirectionsWaypoint 字段过多。请参阅下文的航点限制部分。
		5.MAX_ROUTE_LENGTH_EXCEEDED 表示所请求的路线过长，无法进行处理。当系统返回更复杂的路线时，就会发生此错误。不妨尝试减少航点、转弯或指示的数量。
		6.INVALID_REQUEST 表示提供的 DirectionsRequest 无效。导致出现此错误代码的最常见原因包括：请求中缺少出发地或目的地；或者公交请求中包含航点。
		7.OVER_QUERY_LIMIT 表示网页在允许的时间段内发送的请求过多。
		8.REQUEST_DENIED 表示不允许网页使用路线服务。
		9.UNKNOWN_ERROR 表示因服务器错误而无法处理路线请求。如果您重试，请求可能会成功。
		*/

		calcRouteButton.addEventListener('click',calcRoute);
		function calcRoute(){
		  var start = document.getElementById('pos1').value;
		  var end = document.getElementById('pos2').value;
		  if(!start || !end) {return;}

		  start=JSON.parse(start);
		  end=JSON.parse(end);

		  var request = {
		    origin: start,
		    destination: end,
		    travelMode: 'DRIVING'
		  };
		  directionsService.route(request, function(result, status) {
		    if (status == 'OK') {
				directionsRenderer.setDirections(result);

				var leg = result.routes[0].legs[0];

				route_obj.address_start = leg.start_address;
				route_obj.address_end = leg.end_address;
				route_obj.distance = leg.distance.text;
				route_obj.distance_value = (leg.distance.value*1/1000).toFixed(2);
				route_obj.duration = leg.duration;
				console.log(route_obj);

				var routeInfo ="<div style='color:#f60'>【出发】:"+leg.start_address+"</div>";
				routeInfo +="<div style='color:#0f0'>【终点】:"+leg.end_address+"</div>";
				routeInfo +="<div>【距离】:"+leg.distance.text+"</div>";
				routeInfo +="<div>【预计时间】:"+leg.duration.text+"</div>";

				setInfo(end,routeInfo,map);

		    }else{
		    	console.log(status);
		    }
		  });
		}	


		//显示货车位置
		function showTruckPosition(pos){
				const image ="/upload/20230309/truck.png";
				var marker=new google.maps.Marker({
				position:pos,
				map,
				icon:image
				//,animation:google.maps.Animation.BOUNCE //一动一动的图标
			});

		}



		//建立信息窗口
		function setInfo(pos,text,map){
			infoWindow.setMap(null);
			infoWindow=null;
			infoWindow = new google.maps.InfoWindow({content:text});
			infoWindow.setPosition(pos); //建立一个info
			infoWindow.open(map); //info放进地图上
			//map.setCenter(pos);  //地图中心移动到pos上
		}


		outCalcRoute = calcRoute;
		outTruckPos = showTruckPosition;
		outWhereIsHere = whereIsHere;
		
	}

	window.onload = loadScript;
	


	$("document").ready(function(){


	})


</script>